package tr.helper;

import java.lang.reflect.Field;
import lombok.extern.slf4j.Slf4j;

/**
 * test-mock
 *
 * @author MrYe
 * @date 2021-11-17 17:39
 */
@Slf4j
public final class ReflectUtil {

    private ReflectUtil() {
    }

    /**
     * 可修改私有属性
     *
     * @param bean  要修改的bean
     * @param name  字段名
     * @param value 值
     */
    public static void setFieldValue(Object bean, String name, Object value) {
        final Field field;
        try {
            field = bean.getClass().getDeclaredField(name);
            final boolean accessible = field.isAccessible();
            if (!accessible) {
                field.setAccessible(true);
            }
            field.set(bean, value);
            field.setAccessible(accessible);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public static Object getFieldValue(Object obj, String fieldName) {
        final Field field;
        try {
            field = obj.getClass().getDeclaredField(fieldName);
            final boolean accessible = field.isAccessible();
            if (!accessible) {
                field.setAccessible(true);
            }
            final Object value = field.get(obj);
            field.setAccessible(accessible);
            return value;
        } catch (Exception e) {
            log.error("", e);
            return null;
        }

    }

}
